/**
 * Created by yz on 2017/8/23.
 */
"use strict";
console.log('share');
//全局变量
var flag = true;
if(is_weixn()) {
    // $(".videoPlay").remove();
    var weixn = true;
};
//判断是否是微信打开
function is_weixn(){
    var ua = navigator.userAgent.toLowerCase();
    if(ua.match(/MicroMessenger/i)=="micromessenger") {
        return true;
    } else {
        return false;
    }
};

function is_uc() {
    if(navigator.userAgent.indexOf('UCBrowser') > -1) {
        return true;
    }else{
        return false;
    }
};

//判断是否安装app，没有这跳转到下载
$(".downloadApp").click(function () {
    console.log('getApp');
    var ua = navigator.userAgent.toLowerCase();
    var config = {
        /*scheme:必须*/
        // scheme_IOS: 'sinaweibo://home',
        // scheme_Adr: 'sinaweibo://splash',
        // scheme_Adr: 'weixin://',
        scheme_IOS: 'Coolface://',
        scheme_Adr: 'app://com.yxkj.youdoneed',
        // download_IOS: 'https://www.pgyer.com/IuLm',
        // download_Adr: 'https://www.pgyer.com/E8SB',
        download_IOS: 'itms-apps://itunes.apple.com/us/app/coolface/id1246578323?l=zh&ls=1&mt=8',
        download_Adr: 'http://a.app.qq.com/o/simple.jsp?pkgname=com.yxkj.youdoneed',
        timeout: 600
    };
    openclient();
    function openclient() {
        var startTime = Date.now();
        var ifr = document.createElement('iframe');
        ifr.src = ua.indexOf('os') > 0 ? config.scheme_IOS : config.scheme_Adr;
        // alert(ifr.src);
        ifr.style.display = 'none';
        document.body.appendChild(ifr);
        var t = setTimeout(function() {
            var endTime = Date.now();
            // alert(endTime);
            // alert(startTime)
            // alert(endTime - startTime > config.timeout + 200);
            // alert(!startTime)
            if (!startTime || endTime - startTime < config.timeout + 200) { //如果装了app并跳到客户端后，endTime - startTime 一定> timeout + 200
                // alert(ua.indexOf('os') > 0 ? config.download_IOS : config.download_Adr);
                window.location = ua.indexOf('os') > 0 ? config.download_IOS : config.download_Adr;
            }
        }, config.timeout);
        window.onblur = function() {
            clearTimeout(t);
        }
    }
});

//点击展示所有评论
$(document).on('click','.commentCount',function () {
    if(flag) {
        $(this).parent().css('height','auto');
        $(this).siblings(".subComment").css('display','block');
        flag = false;
    } else {
        $(this).parent().css('height','70px');
        $(this).siblings(".subComment").css('display','none');
        $(this).parent().children(".subComment:first-child").css('display','block');
        flag = true;
    }
})
    //播放视频
    .on('click', '.modal .play', function () {
        $(this).siblings().get(0).play();
    })
    //暂停视频
    .on('click', '.modal video', function () {
        $(this).get(0).pause();
        $(".modal .play").show();
    })
    //根据点击的类型填入浮层
    .on('click', '.resource img', function() {
        // alert('1')
        if($(this).parent().parent().attr('data-type') === 'music' || $(this).parent().attr('data-type') === '3dVideo') {
            return
        }
        $(".modal").css('display', 'block');
        if($(this).parent().attr('data-type') === 'video') {
            $(".videoPlay").css('display','none');
            // if(is_weixn()) {
            //     $(".videoPlay").remove();
            //     $(".modal").css('display', 'none');
            //     return false;
            // };
            var poster = $(this).attr('poster') ? "poster=" + $(this).attr('poster') : "";
            // $(".modal .content").append("<iframe src='./ifream.html'></iframe>")

            if($(this).parent().attr('data-mediaDirection') === 2) {
                //根据方向填入不同的视频
                $(".modal .content").append("<video "+poster+" style='width:100%;'><source src="+(is_uc() ? $(this).parent().attr('data-url') : $(this).parent().find('video source').attr('src')) +" type=' video/mp4'><source src="+(is_uc() ? $(this).parent().attr('data-url') : $(this).parent().find('video source').attr('src'))+" type='video/ogg'></video>");
            }else {
                $(".modal .content").append("<video "+poster+" style='position:absolute;top: 50%;width:100%;transform: translateY(-50%);object-fit: fill;'><source src="+(is_uc() ? $(this).parent().attr('data-url') : $(this).parent().find('video source').attr('src'))+" type=' video/mp4'><source src="+(is_uc() ? $(this).parent().attr('data-url') : $(this).parent().find('video source').attr('src'))+" type='video/ogg'></video>");
            };
            $(".modal video")[0].play();
            $(".modal .content").append("<div class='play'></div>");
            $(".modal video")[0].onplaying = function () {
                $(".modal .play").hide();
            };
        }else if($(this).parent().attr('data-type') === 'image')  {
            if($(this).height()/$(this).width() > 1.4) {
                 //    图片铺满整个页面
                $(".modal .content").append("<img style='position:absolute;width:100%;' src="+$(this).attr('src')+" >");
            }else{
                $(".modal .content").append("<img style='position:absolute;top: 50%;width:100%;transform: translateY(-50%);' src="+$(this).attr('src')+" >");
            }
            // $(".modal .content").append("<img style='position:absolute;top: 50%;width:100%;transform: translateY(-50%);' src="+$(this).attr('src')+" >");
            // $(".modal .content").append("<img style='position:absolute;width:100%;' src="+$(this).attr('src')+" >");
        }else {
            return
        };
    })
    //点击关闭浮层
    .on('click', '.close', function () {
        $(".modal").css('display', 'none');
        $(".videoPlay").css('display','block');
        $(".modal .content").empty();
        return false;
    })
    //音乐播放与暂停
    .on('click', '.other .musicPlay', function () {
        if($('.song audio').get(0).paused) {
            $('.song audio').get(0).play();
            $(this).attr('src', 'http://youdoneed-test.oss-cn-shenzhen.aliyuncs.com/161a6qm0vqv7czxtoh5a.jpg');
        }else{
            $('.song audio').get(0).pause();
            $(this).attr('src', 'http://youdoneed-test.oss-cn-shenzhen.aliyuncs.com/161a6qm0vqv7czxtoh5c.jpg');
        }
    });

function ajax(url, param, type) {
    // 利用了jquery延迟对象回调的方式对ajax封装，使用done()，fail()，always()等方法进行链式回调操作
    return $.ajax({
        url: url,
        data: param || {},
        type: type || 'GET',
        dataType: "json"
    });
};

//判断url是本地还是服务器的
var str=location.href;
var idList1 = str.split('?')[1];
if(idList1) {
    var id = idList1.split('=')[1];
};
var url = '';
if(str.indexOf('localhost') > -1) {
    url = "";
}else {
    // url = "http://" + window.location.host;
    // url = window.location.origin + '/coolface';
    url = '..'
};
var url1 = url + "/community/forummessage/getForumMsgDetail?forumMsgId=";
var url2 = url + "/community/forumcomment/getForumcommentByForumMsgId?offset=1&limit=100";
getDetail(url1,id);

/*
 *  getDetail 获取帖子详情
 */
function getDetail(url, id) {
    var newUrl = url + id;
    ajax(newUrl).done(function (resp) {
        console.log(resp);
        var data = resp;
        if(data.success) {
            //判断是否分享帖，如果是分享帖直接显示原贴信息
            if(data.data.sourceId && data.data.msgType != 'shareGroup') {
                ajax(url+data.data.sourceId).done(function (resp) {
                    if(resp.success){
                        // if(resp.data.msgType === 'threeDimensionalVideo') {
                        //     console.log('123');
                        // }
                        getComment(url2, resp.data.userId, id);
                        romanceData(resp.data);
                    }else {
                        $('body').css('display', 'block')
                            .empty()
                            .append("<div style='padding-top: 45%;text-align: center;'><img style='width: 60%;' src='http://youdoneed-test.oss-cn-shenzhen.aliyuncs.com/1619yqi6skyjjq8dobeh.jpg' alt=''><p>Sorry,"+resp.message+"</p></div>");
                    };
                }).fail(function (err) {
                    
                });
            }else{
                // if(data.data.msgType === 'threeDimensionalVideo') {
                //     console.log('123');
                //     window.location.href = 'http://coolface.youdoneed.com/share/3Dshare.html?id=8c7448bfb1554e9191b90021cff4dd87&length=135&musicUrl=http://youdoneed-test.oss-cn-shenzhen.aliyuncs.com/1537.mp3';
                // }else {
                //
                // }
                getComment(url2, data.data.userId, id);
                romanceData(data.data);
            };
        }else {
            $('body').css('display', 'block')
                           .empty()
                           .append("<div style='padding-top: 45%;text-align: center;'><img style='width: 60%;' src='http://youdoneed-test.oss-cn-shenzhen.aliyuncs.com/1619yqi6skyjjq8dobeh.jpg' alt=''><p>Sorry,"+resp.message+"</p></div>");
        }
    }).fail(function (err) {

    });
};
/*
 *  getComment 获取帖子评论
 */
function  getComment(url, param1, param2) {
    var newUrl = url + '&userId=' + param1 + '&forumMsgId=' + param2;
    ajax(newUrl).done(function (resp) {
        console.log(resp);
        var data = resp;
        if(data.success) {
            //判断是否存在评论
            if(data.data && data.data.length > 0){
                $(".comment").css('display','block');
                $(".commentBody").remove();
                var comment = data.data;
                for(var i = 0;i < comment.length; i++){
                    var temp = $("#commentTemp").clone().html();
                    //评论用户昵称
                    var html = temp.replace("用户昵称01", comment[i].userNickname);
                    html = html.replace('headerImage', comment[i].userHeadUrl);
                    //评论时间
                    html = html.replace("10分钟前", timeChange(comment[i].createDate));
                    //评论内容
                    html = html.replace("content1", comment[i].content);
                    //评论图片
                    if(comment[i].commentPicUrl) {
                        html = html.replace("defaultImg",comment[i].commentPicUrl);
                    } else {
                        html = html.replace("commentImg","commentImg hidden");
                    }
                    //如果存在子评论
                    if(comment[i].listForumcomment.length>0){
                        var commentList = comment[i].listForumcomment;
                        var text = '';
                        for(var j = 0;  j< commentList.length; j++) {
                            text += "<div class='subComment'><p class='title'>"+commentList[j].userNickname+"回复"+comment[i].userNickname+"</p><p class='text'>"+commentList[j].content+"</p></div>";
                        };
                        text += "<p class='commentCount'>共"+commentList.length+"条回复<i class='icon iconfont1 icon-xiangyou'></i></p>"
                        html = html.replace("回复",text);
                    }else {
                        html = html.replace("reply","reply hidden");
                        // $('.reply').remove();
                    };
                    $('.empty').before(html);
                    var height = $(".commentBody").eq(i).find(".subComment:first-child").height();
                    if(height) {
                        $(".commentBody").eq(i).find(".reply").height(height+30)
                    };
                };
            }else{
                return;
                // $('.comment').empty();
                // $('.comment').append("<div class='NoComment'><img src='image/empty.jpg'></div><p class='NoCommetText'>还没有人评论，有些寂寞</p>");
            }
        }else {
            return;
        }
    }).fail(function (err) {

    });
}

/*
 *  romanceData 渲染数据到页面方法
 *  @param data
 */
function romanceData(data) {
    $('body').css('display', 'block');
    //用户头像
    $('.userImg').css('backgroundImage', 'url('+data.userHeadUrl+')');
    $('.userName').html(data.nickName);
    $(".desc .address").html(data.postionLabel === null ? '' : data.postionLabel);
    //标签加内容
    var text = '';
    // if(data.listForummessagelabel.length>0){
    //     //内容
    //     for(var i = 0; i< data.listForummessagelabel.length; i++) {
    //         text += "<span style='color: blueviolet'>#"+data.listForummessagelabel[i].labelDescribe+"#</span>";
    //     };
    // };
    text = data.msgContent;
    if(text !== 'null') {
        $('.text p').html(text);
    };
    //发帖时间
    $(".message .desc .time").html(timeChange(data.createDate));
    // 媒体资源
    $('.other').empty();
    var html = '';
    for(var j = 0; j < Math.min(2, data.listForummediaresource.length); j++) {
        html = tempAdd(data.listForummediaresource[j]);
        $('.other').append(html);
    };
    if(data.listForummediaresource.length > 2) {
        $(".showAll").css('display', 'block');
        $(".showAll .resourceNum").html(data.listForummediaresource.length);
    }
};
//将音乐或视频添加到页面上
function tempAdd(obj) {
    if(obj.mediaType === 'picture' || obj.mediaType === 'gif') {
        return "<div data-type='image' style='position: relative'><img style='width:100%;height: 100%;' src="+(obj.imageUrl == null ? obj.videoUrl : obj.imageUrl)+" ></div>";
    }else if(obj.mediaType === 'video' || obj.mediaType === 'shortVideo') {
        //获取视频时长以及视频宽高比
        var id = parseInt(Math.random()*1000000);
        var mediaDirection = 1;
        var cls = 'class'+ id;
        $('body').append("<video src='' id="+ id +" style='display: none'></video>")
        $("#"+id).prop("src",obj.videoUrl);
        $("#"+id)[0].addEventListener("loadedmetadata", function() {
            $("."+cls).attr('data-mediaDirection', this.videoHeight/this.videoWidth >1.1 ? 2 : 1);
            mediaDirection: this.videoHeight/this.videoWidth >1.1 ? 2 : 1;
        });
        $("#"+id).remove();
        // var html = "<div controls data-type='video'  class="+cls+" data-mediaDirection="+mediaDirection+" style='position: relative'><img class='videoPlay' src='http://youdoneed-test.oss-cn-shenzhen.aliyuncs.com/161a6qm0vqv7czxtoh5c.jpg' style='width: auto;position: absolute;left: 50%;top: 50%;transform: translate(-50%,-50%);' alt=''><video class='video'  poster="+obj.imageUrl+"  style='width:100%;object-fit: fill;'><source src="+obj.videoUrl+" type=' video/mp4'><source src="+obj.videoUrl+" type='video/ogg'></video></div>";
            var html ='';
        // if(is_weixn) {
            //微信环境下不让其打开弹出层播放视频
            // html = "<div data-type='video'  class="+cls+" data-mediaDirection="+mediaDirection+" style='position: relative'><img class='videoPlay' src='http://youdoneed-test.oss-cn-shenzhen.aliyuncs.com/161a6qm0vqv7czxtoh5c.jpg' style='width: auto;position: absolute;left: 50%;top: 50%;transform: translate(-50%,-50%);' alt=''><video class='video' poster="+(obj.imageUrl?obj.imageUrl:'')+" style='width:100%;object-fit: fill;'><source src="+obj.videoUrl+" type=' video/mp4'><source src="+obj.videoUrl+" type='video/ogg'></video></div>"
            if(!navigator.userAgent.match(/android/i)) {
                //ios系列下
                //x-webkit-airplay='allow'  muted playsinline webkit-playsinline='true'
                html = "<div data-type='video'  class="+cls+" data-mediaDirection="+mediaDirection+" style='position: relative'><video  controls poster="+(obj.imageUrl?obj.imageUrl:'')+" style='width:100%;object-fit: fill;'><source src="+obj.videoUrl+" type=' video/mp4'><source src="+obj.videoUrl+" type='video/ogg'></video></div>";
            }else{
                //安卓系列下
                //x5-video-player-type='h5' x5-video-player-fullscreen='true' x-webkit-airplay='true' playsinline webkit-playsinline='true'
                if(is_uc()) {
                    //uc浏览器兼容处理
                    // html = "<div data-type='video'  class="+cls+" data-mediaDirection="+mediaDirection+" style='position: relative'><img class='videoPlay' src='http://youdoneed-test.oss-cn-shenzhen.aliyuncs.com/161a6qm0vqv7czxtoh5c.jpg' style='width: auto;position: absolute;left: 50%;top: 50%;transform: translate(-50%,-50%);z-index: 10;' alt=''><video class='video' poster="+(obj.imageUrl?obj.imageUrl:'')+" style='width:100%;object-fit: fill;'><source src="+obj.videoUrl+" type=' video/mp4'><source src="+obj.videoUrl+" type='video/ogg'></video></div>";
                    html = "<div data-type='video'  class="+cls+" data-mediaDirection="+mediaDirection+" data-url="+obj.videoUrl+" style='position: relative'><img class='videoPlay' src='http://youdoneed-test.oss-cn-shenzhen.aliyuncs.com/161a6qm0vqv7czxtoh5c.jpg' style='width: auto;position: absolute;left: 50%;top: 50%;transform: translate(-50%,-50%);z-index: 10;' alt=''><img src="+obj.imageUrl+" alt=''>";
                }else{
                    // html = "<div data-type='video'  class="+cls+" data-mediaDirection="+mediaDirection+" style='position: relative'><img class='videoPlay' src='http://youdoneed-test.oss-cn-shenzhen.aliyuncs.com/161a6qm0vqv7czxtoh5c.jpg' style='width: auto;position: absolute;left: 50%;top: 50%;transform: translate(-50%,-50%);' alt=''><video x5-video-player-type='h5' x5-video-player-fullscreen='true' controls class='video' poster="+(obj.imageUrl?obj.imageUrl:'')+" style='width:100%;object-fit: fill;'><source src="+obj.videoUrl+" type=' video/mp4'><source src="+obj.videoUrl+" type='video/ogg'></video></div>"
                    html = "<div data-type='video'  class="+cls+" data-mediaDirection="+mediaDirection+" style='position: relative'><video webkit-playsinline='true' controls class='video' poster="+(obj.imageUrl?obj.imageUrl:'')+" style='width:100%;object-fit: fill;height: 100%;'><source src="+obj.videoUrl+" type=' video/mp4'><source src="+obj.videoUrl+" type='video/ogg'></video></div>"
                }
            }
        // }
        return html;
    }else if(obj.mediaType === 'music') {
        $(".song audio , .song audio source").attr('src', obj.songUrl);
        var html1 = '';
        if(obj.imageUrl == null) {
            html1 = "<div data-type='music' style='position: relative;height: 86px;border: 1px solid #ccc;padding: 10px;box-sizing: border-box;'><div style='height: 100%;width: 20%;float: left;position: relative;'><img class='musicPlay' src='http://youdoneed-test.oss-cn-shenzhen.aliyuncs.com/161a6qm0vqv7czxtoh5c.jpg' style='width: auto;position: absolute;left: 50%;top: 50%;transform: translate(-50%,-50%);' alt=''><img style='width:100%;height: 100%;' src='http://youdoneed-test.oss-cn-shenzhen.aliyuncs.com/161a6qm0vqv7czxtoh5b.jpg'></div><div style='width: 75%;float: right;height: 100%;'><p style='font-size: 14px;'>"+obj.songName+"</p><p style='font-size: 12px;'>"+obj.singerName+"</p></div></div>";
        }else {
            html1 = "<div data-type='music' style='position: relative;height: 86px;border: 1px solid #ccc;padding: 10px;box-sizing: border-box;'><div style='height: 100%;width: 20%;float: left;position: relative;'><img class='musicPlay' src='http://youdoneed-test.oss-cn-shenzhen.aliyuncs.com/161a6qm0vqv7czxtoh5c.jpg' style='width: auto;position: absolute;left: 50%;top: 50%;transform: translate(-50%,-50%);' alt=''><img style='width:100%;height: 100%;' src="+obj.imageUrl+"></div><div style='width: 75%;float: right;height: 100%;'><p style='font-size: 14px;'>"+obj.songName+"</p><p style='font-size: 12px;'>"+obj.singerName+"</p></div></div>";
        };
        return html1;
    }else if(obj.mediaType === 'threeDimensionalVideo') {
        var videoId = location.href.split('?')[1].split('=')[1];
        var data = 'videoId='+videoId;
        ajax('/common/getvideoScreenImgs', data, 'POST').then(function (resb) {
            console.log(resb)
            var url = "3Dshare.html?id="+videoId+"&length="+resb.data.size+"&musicUrl="+resb.data.musicUrl;
            $('#3dVideo').attr('href', url);
        });
        return "<a id='3dVideo' data-type='3dVideo' style='display: block;position: relative'><img style='width:100%;height: 100%;' src="+obj.imageUrl+" ></a>";
        // $.ajax({
        //     type: 'POST',
        //     url: '/common/getvideoScreenImgs',
        //     data: data,
        //     success: function (resb) {
        //         console.log(resb);
        //         var url = "3Dshare.html?id="+videoId+"?length="+resb.data.size+"?musicUrl="+resb.data.musicUrl;
        //         $('#3dVideo').attr('href', url);
        //     },
        //     error: function (err) {
        //
        //     }
        // })
    }
}

/*
*  timeChange时间格式化方法
*  @param time 要格式化的时间，格式为1990-01-01
 */
function timeChange(time) {
    var timestamp1 = Date.parse(new Date());
    var timestamp2 = Date.parse(time.replace(/-/g, "/"));
    if((timestamp1 - timestamp2) >= 86400000) {
        return time;
    }else if( 86400000 > (timestamp1 - timestamp2) && (timestamp1 - timestamp2) >= 3600000) {
        return Math.floor((timestamp1 - timestamp2)/3600000) > 24 ? time : Math.floor((timestamp1 - timestamp2)/3600000)+"小时前";
    }else if( 3600000 > (timestamp1 - timestamp2) && (timestamp1 - timestamp2) >= 600000) {
        return Math.floor((timestamp1 - timestamp2)/60000) > 60 ? time : Math.floor((timestamp1 - timestamp2)/60000)+"分钟前";
    }else{
        return '刚刚'
    }
}
